//
//  DiscoverySearchViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/9/2.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "DiscoverySearchViewController.h"
#import "MeatSearchShopViewController.h"
#import "FMTagsView.h"
#import "MeatSearchErrorOrEmptyTableViewCell.h"

#import "DiscoveryActicleViewController.h"
#import "FoundActicleTypeModel.h"
#import "XXPageTabView.h"


@interface DiscoverySearchViewController ()<UITextFieldDelegate, FMTagsViewDelegate, UIScrollViewDelegate, XXPageTabViewDelegate>

@property (strong, nonatomic) UIView * navView;
@property (strong, nonatomic) UITextField *searchTextField;
@property (strong, nonatomic) UIButton *cancelButton;

@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) UILabel *historyTitleLabel;
@property (strong, nonatomic) UIButton *historyDeleteButton;
@property (strong, nonatomic) FMTagsView *historyTagView;      //历史搜索记录

@property (strong, nonatomic) UILabel *hotTitleLabel;
@property (strong, nonatomic) FMTagsView *hotTagView;          //热门搜索

@property (strong, nonatomic) NSMutableArray *dataArray;
@property (strong, nonatomic) NSMutableArray *historyArray;

@property (assign, nonatomic) BOOL isGetDataSuccess; //是否获取数据失败
@property (assign, nonatomic) BOOL isNotNeedSaveHistory;    //是否不需要保存历史搜索记录

@property (nonatomic , strong) XXPageTabView *pageTabView;
@property (nonatomic, strong) NSArray *childTitles;


@end

@implementation DiscoverySearchViewController

#pragma mark - lifecycle methods

- (void)setupUI{
    
    self.view.backgroundColor = KWhiteColor;
    self.baseNavView.hidden = YES;
    
    _dataArray = [NSMutableArray array];
    _historyArray = [NSMutableArray array];
    _isNotNeedSaveHistory = NO;
    
    [self initArrayData];
    
    [self.view addSubview:self.navView];
    [self.searchTextField becomeFirstResponder];
    [self.view addSubview:self.scrollView];
    
    [self reloadTagsView];
}

#pragma mark - networking methods

- (void)reloadTagsView
{
    float historyViewBottom = 30;
    
    if (self.historyArray.count > 0) {
        self.historyTitleLabel.hidden = NO;
        self.historyDeleteButton.hidden = NO;
        self.historyTagView.hidden = NO;
        self.historyTagView.tagsArray = self.historyArray;
        self.historyTitleLabel.top = historyViewBottom;
        self.historyDeleteButton.mj_y = historyViewBottom;
        self.historyTagView.mj_y = self.historyTitleLabel.bottom + 15;
        self.scrollView.contentSize = CGSizeMake(KScreenWidth, self.historyTagView.bottom+30);
        
    }else {
        self.historyTitleLabel.hidden = YES;
        self.historyDeleteButton.hidden = YES;
        self.historyTagView.hidden = YES;
        
        if (self.historyTagView.hidden != YES) {
            self.scrollView.contentSize = CGSizeMake(KScreenWidth, self.historyTagView.bottom+30);
        }else {
            self.scrollView.contentSize = CGSizeMake(KScreenWidth,self.scrollView.height);
        }
    }
}

- (void)initArrayData
{
    //获取缓存的历史记录
    if ([kUserDefaults arrayForKey:kUserFoundActicleSearchHistory]) {
        [_historyArray addObjectsFromArray:[kUserDefaults arrayForKey:kUserFoundActicleSearchHistory]];
    }
}


#pragma mark - delegate
- (void)scrollToLast:(id)sender {
    [self.pageTabView setSelectedTabIndexWithAnimation:self.pageTabView.selectedTabIndex-1];
}

- (void)scrollToNext:(id)sender {
    [self.pageTabView setSelectedTabIndexWithAnimation:self.pageTabView.selectedTabIndex+1];
}

- (void)pageTabViewDidEndChange{
    
}


#pragma mark - FMTagsViewDelegate
- (void)tagsView:(FMTagsView *)tagsView didSelectTagAtIndex:(NSUInteger)index
{
    NSString * keyword = self.historyArray[index];
    if (keyword) {
        [kNotificationCenter postNotificationName:NotificationFoundActicleSearch object:keyword];
    }
}

#pragma mark - textfield delegate
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    //如果键盘取消 需要将当前搜索内容当做搜索记录保存
    if (textField == self.searchTextField) {
        if (_isNotNeedSaveHistory != YES) {
            if (self.searchTextField.text.length > 0) {
                if ([kUserDefaults arrayForKey:kUserFoundActicleSearchHistory]) {
                    NSArray * array = [kUserDefaults arrayForKey:kUserFoundActicleSearchHistory];
                    
                    for (NSString *str in array) {
                        if ([str isEqualToString:self.searchTextField.text]) {
                            //判断 当前搜索字段已包含则直接退出 不处理
                            return;
                        }
                    }
                    
                    NSMutableArray * newArray = [NSMutableArray arrayWithArray:array];
                    //如果数组为10条 需要删除1条 再插入一条，限制最多10条
                    if (newArray.count >= 10) {
                        [newArray removeLastObject];
                    }
                    [newArray insertObject:self.searchTextField.text atIndex:0];
                    NSArray * lastArray = [NSArray arrayWithArray:newArray];
                    [kUserDefaults setObject:lastArray forKey:kUserFoundActicleSearchHistory];
                    [kUserDefaults synchronize];
                }else {
                    NSArray * array = [NSArray arrayWithObject:self.searchTextField.text];
                    [kUserDefaults setObject:array forKey:kUserFoundActicleSearchHistory];
                    [kUserDefaults synchronize];
                }
                if (_historyArray.count >= 10) {
                    [_historyArray removeLastObject];
                }
                [_historyArray insertObject:self.searchTextField.text atIndex:0];
                [self reloadTagsView];
            }
        }else {
            _isNotNeedSaveHistory = NO;
        }
    }
}


#pragma mark - tableview.datasource methods

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.searchTextField resignFirstResponder];
}


#pragma mark - setter methods
- (void)setTitles:(NSArray *)titles{
  
    NSMutableArray *aims = [NSMutableArray array];
    [titles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        FoundActicleTypeItem *item = (FoundActicleTypeItem *)obj;
        [aims addObject:item.text];
        
        DiscoveryActicleViewController *vc = [[DiscoveryActicleViewController alloc] init];
        vc.type = item.value;
        [self addChildViewController:vc];
        
    }];
    
    self.childTitles = [aims copy];
    [self.view addSubview:self.pageTabView];
    
    [self.pageTabView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(TJ_NavBarHeight);
    }];
}


#pragma mark - getter methods

- (UIView *)navView
{
    if (!_navView) {
        _navView = [UIView makeViewBgColor:KWhiteColor cornerRadius:0];
        _navView.frame = CGRectMake(0, TJ_StatusBarHeight_Define, KScreenWidth, 44);
        
        UIView *searchView = [UIView makeViewBgColor:UIColorFromRGB(0xF7F7F7) cornerRadius:17];
        searchView.frame = CGRectMake(15, 3, KScreenWidth-15-58, 34);
        [self addShadowAndCircleCorner:searchView.layer corner:17];
        [_navView addSubview:searchView];
        
        UIImageView *searchImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 34, 34)];
        searchImgView.image = [UIImage imageNamed:@"meat_buy_search"];
        searchImgView.contentMode = UIViewContentModeCenter;
        [searchView addSubview:searchImgView];
        
        [searchView addSubview:self.searchTextField];
        [_navView addSubview:self.cancelButton];
        self.cancelButton.centerY = searchView.centerY;
    }
    return _navView;
}


- (UITextField *)searchTextField
{
    if (!_searchTextField) {
        _searchTextField = [[UITextField alloc]initWithFrame:CGRectMake(34, 0, KScreenWidth-15-34-80, 34)];
        _searchTextField.placeholder = @"搜索内容";
        _searchTextField.delegate = self;
        _searchTextField.textColor = UIColorFromRGB(0xB2B2B2);
        _searchTextField.font = mFont(14);
        _searchTextField.returnKeyType = UIReturnKeySearch;
    }
    return _searchTextField;
}

- (UIButton *)cancelButton
{
    if (!_cancelButton) {
        _cancelButton = [UIButton makeButtonWithText:@"取消" textColor:UIColorFromRGB(0x666666) font:mFont(14) textAliment:1 cornerRadius:0];
        _cancelButton.frame = CGRectMake(KScreenWidth- 58, 0, 58, 44);
        
        @weakify(self);
        _cancelButton.tapBlock = ^{
            @strongify(self);
            self.searchTextField.text = @"";
            [self.searchTextField resignFirstResponder];
            [self.dataArray removeAllObjects];
            self.tableView.hidden = YES;
            [self dismissViewControllerAnimated:YES completion:nil];
        };
    }
    return _cancelButton;
}


- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, self.navView.bottom, KScreenWidth, KScreenHeight-self.navView.bottom -TJ_SafeAreaBottomHeight)];
        _scrollView.delegate = self;
        
        [_scrollView addSubview:self.historyTitleLabel];
        [_scrollView addSubview:self.historyDeleteButton];
        [_scrollView addSubview:self.historyTagView];
        
    }
    return _scrollView;
}

- (UILabel *)historyTitleLabel
{
    if (!_historyTitleLabel) {
        _historyTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 50, 100, 25)];
        _historyTitleLabel.text = @"搜索历史";
        _historyTitleLabel.textColor = UIColorFromRGB(0x666666);
        _historyTitleLabel.font = mFont(14);
    }
    return _historyTitleLabel;
}

- (UIButton *)historyDeleteButton
{
    if (!_historyDeleteButton) {
        _historyDeleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _historyDeleteButton.frame = CGRectMake(KScreenWidth-50, self.historyTitleLabel.top-5, 50, 35);
        [_historyDeleteButton setImage:[UIImage imageNamed:@"meat_shopcart_cancel"] forState:UIControlStateNormal];
        _historyDeleteButton.isNeedAnimation = YES;
        @weakify(self);
        _historyDeleteButton.tapBlock = ^{
            
            @strongify(self);
            [self showMyAlertWithTitle:@"是否删除搜索记录？" message:nil confirmBtnTitle:@"删除" callBack:^{
                
                if ([kUserDefaults arrayForKey:kUserFoundActicleSearchHistory]) {
                    [kUserDefaults setObject:nil forKey:kUserFoundActicleSearchHistory];
                    [kUserDefaults synchronize];
                    [self.historyArray removeAllObjects];
                    [self reloadTagsView];
                }
            }];
        };
        
    }
    return _historyDeleteButton;
}

- (FMTagsView *)historyTagView
{
    if (!_historyTagView) {
        _historyTagView  = [[FMTagsView alloc] initWithFrame:CGRectMake(15, self.historyTitleLabel.bottom+15, KScreenWidth - 30, 0)];
        _historyTagView.height = KScreenHeight - _historyTagView.mj_y;
        _historyTagView.contentInsets = UIEdgeInsetsZero;
        _historyTagView.tagInsets = UIEdgeInsetsMake(6,15,6,15);
        _historyTagView.tagFont = mFont(12);
        _historyTagView.tagSelectedFont = mFont(12);
        _historyTagView.tagBorderWidth = 1;
        _historyTagView.tagcornerRadius = 14;
        _historyTagView.lineSpacing = 10;
        _historyTagView.interitemSpacing = 10;
        _historyTagView.backgroundColor = KWhiteColor;
        _historyTagView.tagBorderColor = UIColorFromRGB(0xF5F5F5);
        _historyTagView.tagSelectedBorderColor = mMainColor;
        _historyTagView.tagBackgroundColor = mBackgroudColor;
        _historyTagView.tagSelectedBackgroundColor = KWhiteColor;
        _historyTagView.tagTextColor = UIColorFromRGB(0x6F6F6F);
        _historyTagView.tagSelectedTextColor = UIColorFromRGB(0x6F6F6F);
        _historyTagView.delegate = self;
    }
    return _historyTagView;
}


- (XXPageTabView *)pageTabView {
    if (!_pageTabView) {
        _pageTabView = [[XXPageTabView alloc] initWithChildControllers:self.childViewControllers childTitles:self.childTitles];
        _pageTabView.delegate = self;
        _pageTabView.indicatorStyle = XXPageTabIndicatorStyleFollowText;//跟随文本变化长度
        _pageTabView.titleStyle = XXPageTabTitleStyleBlend;//渐变
        _pageTabView.selectedTabIndex = 0;
        _pageTabView.separatorColor = mBackgroudColor;
        _pageTabView.tabItemFont = mFont(15);
        _pageTabView.indicatorHeight = 1;
        _pageTabView.bodyBounces = NO;
        _pageTabView.selectedColor = [UIColor colorWithHexString:@"#53C203"];
        _pageTabView.unSelectedColor = [UIColor colorWithHexString:@"#666666"];
        _pageTabView.tabBackgroundColor = [UIColor clearColor];
        _pageTabView.bodyBackgroundColor = [UIColor clearColor];
        _pageTabView.hidden = YES;
    }
    return _pageTabView;
}


#pragma mark - notifications

- (void)addNotifications{
    
    [kNotificationCenter addObserver:self selector:@selector(textFieldTextDidChanged:) name:UITextFieldTextDidChangeNotification object:self.searchTextField];
}

- (void)removeNotifications{
    [kNotificationCenter removeObserver:self name:UITextFieldTextDidChangeNotification object:self.searchTextField];
}

- (void)textFieldTextDidChanged:(NSNotification *)notification
{
    
    UITextField * textField = notification.object;
    [kNotificationCenter postNotificationName:NotificationFoundActicleSearch object:textField.text];
    
    if (textField == self.searchTextField) {
        if (textField.text.length == 0) {

            self.pageTabView.hidden = YES;
            self.scrollView.hidden = NO;
            
        }else {
            self.pageTabView.hidden = NO;
            self.scrollView.hidden = YES;
        }
    }
}


@end
